from zeus.operation_service.app.core.common.data_collection.prometheus import PrometheusCollector
from zeus.operation_service.app.settings import configuration


def combine_tcp_link_name(entity: dict):
    return f"{entity['machine_id']}_{entity['tgid']}_{entity['client_ip']}_{entity['server_ip']}:{entity['server_port']}"


def combine_cpu_name(entity: dict):
    return f"cpu{entity.get('cpu')}" if entity.get('cpu') != 'cpu' else 'cpu_total'


# 若类型为函数，则返回函数返回值，若为列表，则通过字符串处理
type_name_map = {
    "host": ['hostname'],
    "cpu": combine_cpu_name,
    "proc": ['tgid', 'comm'],
    "block": ['major', 'first_minor'],
    "container": ['name', 'container_id'],
    "app": ['app_name'],
    "sli": ['tgid', 'ins_id', 'app', 'method'],
    "disk": ['disk_name'],
    "nic": ['dev_name'],
    "tcp_link": combine_tcp_link_name,
    "fs": ['MountOn'],
    "net": ['origin'],
    "thread": ['pid', 'tgid', 'comm'],
    "qdisc": ['dev_name', 'handle', 'ifindex'],
    "endpoint": ['tgid', 's_addr'],
    "mem": ['infos']
}


def combine_description_name(entity: dict):
    if type_name_map.get(entity['type']):
        type_value = type_name_map[entity['type']]
        if not isinstance(type_value, list):
            return type_value(entity)
        return "_".join([str(entity[type_name]) for type_name in type_value])
    return entity['key']


def connect_prometheus():
    if not configuration.prometheus or not configuration.prometheus.host or not configuration.prometheus.port:
        return None
    prometheus_server = f'{configuration.prometheus.host}:{configuration.prometheus.port}'
    return PrometheusCollector(server=prometheus_server)


def get_kafka_server():
    if not configuration.kafka or not configuration.kafka.host or not configuration.kafka.port:
        return None
    return f'{configuration.kafka.host}:{configuration.kafka.port}'
